// pages/member/noticeSubmit.js
const util = require('../../utils/util.js');
const apiUrl = require('../../utils/apiUrl.js');
var http = require('../../utils/httpHelper.js');
var dateTimePicker = require('../../utils/dateTimePicker.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    detail: {},
    winWidth: 0,
    winHeight: 0,
    showLoading: false,
    readOnly: false,
    keyboardHeight: 0,
    isIOS: false,
    dateTimeArray: null,
    startTime: null,
    startTimeText: '',
    endTime: null,
    endTimeText: '',
    adminID: 0,
    adminIDs: [],
    adminNames: [],
    adminArray: [],
    popViewShow: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;

    var id = options.id;
    if (id) {
      that.setData({
        id: id,
      });
    }
    var adminID = options.adminID;
    if (adminID) {
      that.setData({
        adminID: adminID,
      });
    }

    var title = options.title;
    if (title) {
      wx.setNavigationBarTitle({
        title: title,
      })
    }

    /**
     * 获取系统信息
     */
    wx.getSystemInfo({

      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });

    // 获取完整的年月日 时分秒，以及默认显示的数组
    var obj = dateTimePicker.dateTimePicker(2000, 2030);

    var nowTimeText = obj.dateTimeArray[0][obj.dateTime[0]] + '-' + obj.dateTimeArray[1][obj.dateTime[1]] + '-' + obj.dateTimeArray[2][obj.dateTime[2]] + ' ' + obj.dateTimeArray[3][obj.dateTime[3]] + ':' + obj.dateTimeArray[4][obj.dateTime[4]] + ':' +
      obj.dateTimeArray[5][obj.dateTime[5]];

    that.setData({
      startTime: obj.dateTime,
      endTime: obj.dateTime,
      startTimeText: nowTimeText,
      endTimeText: nowTimeText,
      dateTimeArray: obj.dateTimeArray,
    });

    const platform = wx.getSystemInfoSync().platform
    const isIOS = platform === 'ios'
    this.setData({
      isIOS
    })

    this.updatePosition(0)
    let keyboardHeight = 0
    wx.onKeyboardHeightChange(res => {
      if (res.height === keyboardHeight) return
      const duration = res.height > 0 ? res.duration * 1000 : 0
      keyboardHeight = res.height
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: 0,
          success() {
            that.updatePosition(keyboardHeight)
            that.editorCtx.scrollIntoView()
          }
        })
      }, duration)

    })

    that.loadAdminData();
  },
  onShow: function () {
    var that = this;
    var noticeData = wx.getStorageSync("noticeData");
    if(noticeData){
      that.setData({
        detail: noticeData,
        startTimeText: noticeData.start_time_text,
        endTimeText: noticeData.end_time_text,
      });
      that.onEditorReady();
      wx.setStorageSync("noticeData", null);
    }
  },
  submit: function (e) {
    var that = this;

    var formData = e.detail.value;

    var title = e.detail.value.title;
    if (title == "") {
      wx.showModal({
        title: '请填写标题'
      });
      return;
    }

    var ID = that.data.id;

    if (ID == 0 && that.data.adminIDs.length == 0) {
      wx.showModal({
        title: '请选择接收人',
      });
      return;
    }

    // console.log(that.data.adminIDs);

    formData['admin_ids'] = that.data.adminIDs;

    formData['start_time'] = util.dateStrChangeTimeTamp(that.data.startTimeText);

    formData['end_time'] = util.dateStrChangeTimeTamp(that.data.endTimeText);

    that.editorCtx.getContents({
      success: (res) => {
        console.log(res);
        if (res.text.length > 0 && res.html != "<p><br></p>") {

          var content = res.html;

          formData["content"] = content;

          that.submitPost(formData);
        } else {
          wx.showModal({
            title: '请填写内容',
          });
          return;
        }
      },
      fail: (err) => {
        wx.showModal({
          title: '提交失败',
        });
        console.log(err);
      }
    });
  },
  submitPost(formData) {
    var that = this;

    wx.showToast({
      title: '正在提交',
      icon: 'loading',
      duration: 2000,
      mask: true,
    });

    var url = apiUrl.UrlNoticeSubmit;

    if (that.data.id > 0) {
      formData["id"] = that.data.id;
    }

    // console.log(formData);
    // return;

    http.ApiPost(url, formData, function (res) {
      if (res.result.errorCode == 1) {
        wx.showToast({
          title: '提交成功！',
          icon: 'success',
          duration: 2000
        });

        wx.setStorageSync("refreshList", "notice");

        console.log("刷新列表");
        wx.navigateBack();
      } else {
        wx.showModal({
          title: res.result.errorMessage
        });
      }
    });
  },
  updatePosition(keyboardHeight) {
    const toolbarHeight = 50
    const {
      windowHeight,
      platform
    } = wx.getSystemInfoSync()
    let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight) : windowHeight
    this.setData({
      editorHeight,
      keyboardHeight
    })
  },
  calNavigationBarAndStatusBar() {
    const systemInfo = wx.getSystemInfoSync()
    const {
      statusBarHeight,
      platform
    } = systemInfo
    const isIOS = platform === 'ios'
    const navigationBarHeight = isIOS ? 44 : 48
    return statusBarHeight + navigationBarHeight
  },
  onEditorReady() {
    const that = this
    wx.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context;
      var detail = that.data.detail;
      if (detail.content) {
        that.editorCtx.setContents({
          html: detail.content,
          success: (res) => {
            console.log(res);
          },
          fail: (err) => {
            console.log(err);
          }
        });
      }
    }).exec()
  },
  blur() {
    this.editorCtx.blur()
  },
  format(e) {
    let {
      name,
      value
    } = e.target.dataset
    if (!name) return
    // console.log('format', name, value)
    this.editorCtx.format(name, value)
  },
  onStatusChange(e) {
    const formats = e.detail
    this.setData({
      formats
    })
  },
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function () {
        console.log('insert divider success')
      }
    })
  },
  clear() {
    this.editorCtx.clear({
      success: function (res) {
        console.log("clear success")
      }
    })
  },
  removeFormat() {
    this.editorCtx.removeFormat()
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },
  textIndent() {
    this.editorCtx.format('textIndent', '2em');
  },
  insertImage() {
    const that = this
    wx.chooseImage({
      count: 9,
      success: function (res) {
        for (let j = 0; j < res.tempFilePaths.length; ++j) {
          that.uploadImage(res.tempFilePaths[j], 0)
        }
      }
    })
  },
  uploadImage: function (path, type) {
    var that = this
    that.showLoading();
    var postData = {};
    var token = wx.getStorageSync("token");
    postData["token"] = token;
    wx.uploadFile({
      url: apiUrl.UrlUpload,
      filePath: path,
      name: 'file',
      formData: postData,
      success: function (res) {
        that.cancelLoading();
        var resdata = JSON.parse(res.data);
        var result = resdata.result;
        if (result.errorCode == 1) {
          wx.hideToast();

          var imgUrl = resdata.url;

          //封面图
          if (type == 1) {
            that.setData({
              coverSrc: imgUrl
            })
          } else {
            that.editorCtx.insertImage({
              src: imgUrl,
              width: '100%',
              success: function () {
                console.log('insert image success');
              }
            })
          }

        } else {
          wx.showModal({
            title: result.errorMessage
          });
        }
      },
      fail: function (err) {
        console.log(err);
        that.cancelLoading();
        wx.showModal({
          title: '上传出错！'
        });
      }
    })
  },
  showLoading: function () {
    this.setData({
      showLoading: true
    })
  },
  cancelLoading: function () {
    this.setData({
      showLoading: false
    })
  },
  changeStartTime(e) {
    var startTime = e.detail.value;
    var dateTimeArray = this.data.dateTimeArray;
    var startTimeText = dateTimeArray[0][startTime[0]] + '-' + dateTimeArray[1][startTime[1]] + '-' + dateTimeArray[2][startTime[2]] + ' ' + dateTimeArray[3][startTime[3]] + ':' + dateTimeArray[4][startTime[4]] + ':' +
      dateTimeArray[5][startTime[5]];
    this.setData({
      startTime: startTime,
      startTimeText: startTimeText
    });
  },
  changeEndTime(e) {
    var endTime = e.detail.value;
    var dateTimeArray = this.data.dateTimeArray;
    var endTimeText = dateTimeArray[0][endTime[0]] + '-' + dateTimeArray[1][endTime[1]] + '-' + dateTimeArray[2][endTime[2]] + ' ' + dateTimeArray[3][endTime[3]] + ':' + dateTimeArray[4][endTime[4]] + ':' +
      dateTimeArray[5][endTime[5]];
    this.setData({
      endTime: endTime,
      endTimeText: endTimeText
    });
  },
  pickerBtnTap: function () {
    var that = this;
    if(that.data.id==0){
      that.setData({
        popViewShow: true,
      });
    }else{
      wx.showModal({
        title: '编辑中不能修改接收人'
      });
    }
    
  },
  //遍历设置选中
  setCheckforData: function (data) {
    var adminIDs = this.data.adminIDs;
    for (let i = 0, lenI = data.length; i < lenI; ++i) {
      data[i].checked = false;
      var tempID = data[i].id.toString();

      if (adminIDs.indexOf(tempID) >= 0) {
        data[i].checked = true;
      }
      data[i].childs = this.setCheckforData(data[i].childs);
    }
    return data;
  },
  //事件处理函数
  tapItem: function (e) {
    var that = this;
    var id = e.detail.id.toString();;
    var item = e.detail.item;
    var adminIDs = that.data.adminIDs;
    var adminNames = that.data.adminNames;

    //取消选中
    if (item.checked) {

      var index = adminIDs.indexOf(id);
      if (index > -1) {
        adminIDs.splice(index, 1);
      }

      var index1 = adminNames.indexOf(item.name);
      if (index1 > -1) {
        adminNames.splice(index1, 1);
      }

    } else {
      adminIDs.push(id);
      adminNames.push(item.name);
      //去重
      adminIDs = util.uniqueArray(adminIDs);
      adminNames = util.uniqueArray(adminNames);
    }

    that.setData({
      adminIDs: adminIDs,
      adminNames: adminNames
    });

    that.setCheck();
  },
  setCheck: function () {
    var that = this;
    var adminArray = that.data.adminArray;
    adminArray = that.setCheckforData(adminArray);

    //默认选中
    if (that.data.adminID > 0) {
      var adminIDs = that.data.adminIDs;
      var adminNames = that.data.adminNames;
      adminArray.map(function (item, index) {
        if (item.id == that.data.adminID) {
          adminIDs.push(item.id);
          adminNames.push(item.name);
          //去重
          adminIDs = util.uniqueArray(adminIDs);
          adminNames = util.uniqueArray(adminNames);
          adminArray[index]['checked'] = true;
        }
      });

      that.setData({
        adminIDs: adminIDs,
        adminNames: adminNames
      });
    }

    that.setData({
      adminArray: adminArray,
    });
  },
  //加载所有数据
  loadAdminData: function () {
    var that = this;

    var parameter = {};

    parameter['all'] = 1;

    http.ApiGet(apiUrl.UrlMemberList, parameter, function (res) {
      if (res.result.errorCode == 1) {
        var newData = res.data;
        if (newData && newData.length > 0) {
          var adminArray = [];

          newData.map(function (item, index) {
            var newItem = {};
            newItem['id'] = item.admin_id;
            newItem['name'] = item.admin_nickname;
            newItem['checked'] = false;
            newItem['childs'] = [];
            adminArray.push(newItem);
          });

          that.setData({
            adminArray: adminArray,
          });

          that.setCheck();
        }
      }
    });
  },
  okBtnTap: function () {
    var that = this;
    that.cancelBtnTap();
  },
  cancelBtnTap: function () {
    var that = this;
    that.setData({
      popViewShow: false
    });
  },
})